<template>
  <section class="area">
    <el-cascader :key="myKey" v-model="value" :props="props" :options="areaoptions" :placeholder="placeholder" :disabled="disabled" filterable clearable style="width: 100%" @change="handleChange" />
  </section>
</template>
<script>
import mixins from './../mixins'
import Area from '@/utils/area'
import request from '@/utils/request'
export default {
  name: 'VArea',
  inject: ['labelClass'],
  mixins: [mixins],
  props: {
    option: {
      value: '',
      props: ''
    }
  },
  data() {
    return {
      area: Area,
      areaoptions: [],
      myKey:0
    }
  },
  computed: {
    props() {
      return this.option.props || undefined
    },
    _labelClass() {
      return this.labelClass()
    }
  },
  watch: {
    areaoptions(val){
      this.myKey++
    },
    area: {
      handler(v) {
        if (this.option.async) {
          return
        }
        if (v) {
          this.areaoptions = this.filterData(v)
        }
      },
      immediate: true
    },
    _labelClass(val){
      this.areaoptions = val
    }
  },
  created() {
    if (this.option.async) {
      this.getList()
    }
    if (this.option.value) {
      if (typeof this.option.value === 'string') {
        this.value = this.option.value.split('/')
      }
    }
  },
  methods: {
    getList() {
      if (this.option.name === 'type') {
        this.areaoptions = this._labelClass
        return
      }
      return new Promise((resolve, reject) => {
        request({
          baseURL: '/API-ENTERPRISE-BACKEND/',
          url: this.option.async,
          method: 'post',
          data: this.option.asyncParams
        }).then(res => {
          this.areaoptions = res.data.data && res.data.data.length > 0 ? res.data.data : []
        })
      })
    },
    filterData(v) {
      v.map(a => {
        if (a.children) {
          if (!a.children.length) {
            delete a.children
          } else {
            this.filterData(a.children)
          }
        }
      })
      return v
    },

    setValue(v) {
      console.log(v, '-=-=-=-=-=')
      if (typeof v === 'string') {
        v = v.split('/')
      }
      this.value = v
    },

    getValue() {
      const { value } = this
      if (value && value.length > 0) {
        if (typeof value === 'string') {
          return value
        } else if (Array.isArray(value)) {
          return value.join('/')
        } else {
          return ''
        }
      } else {
        return ''
      }
    },

    setCheck() {
      const { required, value } = this
      if (required) {
        if (!value || value.length == 0) {
          this.error_ = true
          this.error_message_ = '必填选项不能为空'
        } else {
          this.error_ = false
        }
      } else {
        this.error_ = false
      }
      this.fieldCheck()
    },

    handleChange(e) {
      this.setCheck()
      this.dispatch_event('filed-value-change', e)
    }
  }
}
</script>
